package com.cashmate.struts;

import com.cashmate.hibernate.dao.LoansDAO;
import com.cashmate.hibernate.pojo.Employees;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;

import com.cashmate.hibernate.pojo.Loans;
import com.cashmate.utilities.EnglishNumberToWords;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfAction;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;


import com.opensymphony.xwork2.ActionSupport;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

public class Register_PrintCheck extends ActionSupport{
  private LoansDAO loanDAO = (LoansDAO) ServletActionContext.getServletContext().getAttribute("loansDAO");
  private String selected;
  private String loc;


  @Actions( {
    @Action(value = "/printchecks", results = {
      
    })
  })
  public String execute()
  {
      SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
      SimpleDateFormat format2 = new SimpleDateFormat("MMddyyyy");
      NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.ROOT);
      Employees empl = (Employees) ServletActionContext.getRequest().getSession().getAttribute("employee");
        try {
            loc = "../../loanrelease.jsp?cat=check";
            
//            HashMap<String, List<Loans>> hash = new HashMap<String, List<Loans>>();
            
            HttpServletResponse response = ServletActionContext.getResponse();
            HttpServletRequest request = ServletActionContext.getRequest();
            
              response.setContentType("application/pdf");
                      
              String[] sel = selected.split(",");
              Integer[] sel_int = new Integer[sel.length];
              int count = 0;
              for (String s : sel) {
                  sel_int[count] = Integer.parseInt(s);
                  count++;

              }
              DetachedCriteria criteria = DetachedCriteria.forClass(Loans.class);
              criteria.add(Restrictions.in("loanid", sel_int));            
              criteria.setProjection(null);
              criteria.setResultTransformer(Criteria.ROOT_ENTITY);
              List<Loans> loans = loanDAO.findByCriteria(criteria, 0, sel_int.length);
              
              try{
              Document doc = new Document();
              float f1 = 576;
              float f2 = 216;
              float margintop = 36;
              float marginleft = 56;
              float marginright = 18;
              Rectangle r = new Rectangle(f1, f2);       
              doc.setPageSize(r);
              doc.setMargins(marginleft, marginright, margintop, 0);
              
              PdfWriter writer = PdfWriter.getInstance(doc, response.getOutputStream());
              writer.addViewerPreference(PdfName.PRINTSCALING, PdfName.NONE);       

              doc.open();
              StringBuffer javascript = new StringBuffer();
       
              javascript.append("var params = this.getPrintParams();");

              javascript.append("params.interactive =	params.constants.interactionLevel.silent;");
              javascript.append("params.printerName=\"MY_PRINTER_NAME\";");
              javascript.append("params.pageHandling = params.constants.handling.shrink;");

              PdfAction pdfAction= PdfAction.javaScript(javascript.toString(), writer);
              writer.addJavaScript(pdfAction);

              
              for(Loans l : loans){
                  Loans loan = l;
                  String branchname = l.getBranches().getBranchname();
//                  if(hash.containsKey(branchname)){
//                      hash.get(branchname).add(l);
//                  }else{
//                      hash.put(branchname, new ArrayList<Loans>());
//                      hash.get(branchname).add(l);
//                  }
                  
                  //replaceables
                      String name = loan.getBorrowers().getCompletename();
                      String date = format.format(new Date());
                      
                      double amount = loan.getNetloanableamount();
                  //
              
                  float[] colsWidth = {3f, 1f};
                  PdfPTable ppt = new PdfPTable(colsWidth);
                  ppt.setWidthPercentage(100);
                  ppt.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                  ppt.getDefaultCell().setFixedHeight(22);

                  Font fontInfo = new Font(FontFamily.HELVETICA, 14);
                  Font fontAmt = new Font(FontFamily.HELVETICA, 14, Font.BOLD);

                  Paragraph par = new Paragraph(date, fontInfo);
                  Paragraph par5 = new Paragraph("");          
                  
                  Paragraph par2 = new Paragraph("");
                  
                  try{
                      String dec = nf.format(amount);
                      String point = dec.substring(dec.length() - 2, dec.length());
                      
                      int decimal = Integer.parseInt(point);                
                      if(decimal > 0){
                          par2 = new Paragraph("**"+EnglishNumberToWords.convert((int)amount) +" & " +  decimal + "/100" +" only**", fontAmt);
                      }else{
                          par2 = new Paragraph("**"+EnglishNumberToWords.convert((int)amount) +" only**", fontAmt);
                      }
                      
                  }catch(Exception e){                    
                      e.printStackTrace();
                      par2 = new Paragraph("**"+EnglishNumberToWords.convert((int)amount) +"**", fontAmt);
                  }


                  PdfPCell ppc2 = new PdfPCell(par2);
          //        ppc2.setIndent(36);
                  ppc2.setColspan(2);
                  ppc2.setBorder(Rectangle.NO_BORDER);
                  ppc2.setRowspan(2);
                  ppc2.setFollowingIndent(36);
                  ppc2.setPaddingTop(6);


                  Paragraph par3 = new Paragraph("**"+ name +"**", fontInfo);
                  Paragraph par4 = new Paragraph("**"+ nf.format(amount).substring(2, nf.format(amount).length()) +"**", fontInfo);

                  PdfPCell ppc = new PdfPCell(par3);
                  ppc.setIndent(36);
                  ppc.setFixedHeight(22);
                  ppc.setBorder(Rectangle.NO_BORDER);

                  ppt.addCell(par5);
                  ppt.addCell(par);

                  ppt.addCell(ppc);

                  ppc = new PdfPCell(par4);
                  ppc.setFixedHeight(22);
                  ppc.setBorder(Rectangle.NO_BORDER);

                  ppt.addCell(ppc);
                  ppt.addCell(ppc2);


                  doc.add(ppt); 
                  doc.newPage();
              }
//              <--(Check Register)-->
//              Rectangle rect = new Rectangle(612, 324);
//              doc.setPageSize(rect);
//              doc.setMargins(36, 36, 10, 10);
//              
//              for(String s : hash.keySet()){
//              doc.newPage();
//              
//              PdfPTable  mainT = new PdfPTable(1);
//                mainT.getDefaultCell().setBorder(Rectangle.NO_BORDER);
//                mainT.setWidthPercentage(100);
//
//                Font fontTitle = new Font(FontFamily.HELVETICA, 12, Font.BOLD);
//                Font fontInfoItalic = new Font(FontFamily.HELVETICA, 9, Font.BOLD);
//                Font fontInfoHead = new Font(FontFamily.HELVETICA, 8, Font.BOLDITALIC);
//                Font fontInfo = new Font(FontFamily.HELVETICA, 8);
//
//                PdfPCell tCell = new PdfPCell(new Paragraph("Cashmate Credit Corporation", fontTitle));
//                tCell.setBorder(Rectangle.NO_BORDER);
//                tCell.setHorizontalAlignment(Element.ALIGN_CENTER);
//
//                mainT.addCell(tCell);
//
//                PdfPCell subCell = new PdfPCell(new Paragraph("Check Register Report", fontInfoItalic));
//                subCell.setBorder(Rectangle.NO_BORDER);
//                subCell.setHorizontalAlignment(Element.ALIGN_CENTER);
//
//                mainT.addCell(subCell);
//                
//                float[] desc = {2,4,2,2};
//                PdfPTable descT = new PdfPTable(desc);
//                descT.getDefaultCell().setBorder(Rectangle.NO_BORDER);
//                descT.setWidthPercentage(100);
//                descT.setSpacingBefore(10);
//
//                descT.addCell(new Paragraph("Date:\t", fontInfoItalic));
//                descT.addCell(new Paragraph(format.format(new Date()), fontInfo));
//                descT.addCell(new Paragraph("Branch:\t", fontInfoItalic));
//                descT.addCell(new Paragraph(s, fontInfo));
//
//                mainT.addCell(descT);
//
//                float[] tabs = {4, 1, 2, 2, 2, 2, 2, 2};
//                PdfPTable subT = new PdfPTable(tabs);
//                subT.setWidthPercentage(100);        
//                subT.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
//                subT.setSpacingBefore(10);
//
//                subT.addCell(new Paragraph("Account Name", fontInfoHead));
//                subT.addCell(new Paragraph("Area", fontInfoHead));
//                subT.addCell(new Paragraph("Loan Account", fontInfoHead));
//                subT.addCell(new Paragraph("PN Amount", fontInfoHead));
//                subT.addCell(new Paragraph("Bank Account", fontInfoHead));
//                subT.addCell(new Paragraph("Check No", fontInfoHead));
//                subT.addCell(new Paragraph("Check Date", fontInfoHead));
//                subT.addCell(new Paragraph("Amount", fontInfoHead));
//                
//                for(Loans l : hash.get(s)){
//                    subT.addCell(new Paragraph(l.getCompletename(), fontInfo));
//                    subT.addCell(new Paragraph(l.getAreacode(), fontInfo));
//                    subT.addCell(new Paragraph(l.getAccount(), fontInfo));
//                    subT.addCell(new Paragraph(nf.format(l.getLoanamount()).substring(2, nf.format(l.getLoanamount()).length()), fontInfo));
//                    subT.addCell(new Paragraph(l.getCheck().getBankaccountno(), fontInfo));
//                    subT.addCell(new Paragraph(l.getCheck().getCheckno(), fontInfo));
//                    subT.addCell(new Paragraph(l.getCheck().getCheckdate(), fontInfo));
//                    subT.addCell(new Paragraph(nf.format(l.getNetloanableamount()).substring(2, nf.format(l.getNetloanableamount()).length()), fontInfo));
//                }
//                
//                mainT.addCell(subT);
//
//                PdfPTable subT2 = new PdfPTable(5);
//                subT2.setWidthPercentage(100);
//                subT2.getDefaultCell().setBorder(Rectangle.NO_BORDER);
//                subT2.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
//                subT2.setSpacingBefore(20);
//
//                PdfPCell one = new PdfPCell(new Paragraph(empl.getCompletename(), fontInfo));
//                one.setBorder(Rectangle.BOTTOM);
//                one.setHorizontalAlignment(Element.ALIGN_CENTER);
//
//                subT2.addCell(one);
//                subT2.addCell(new Paragraph(""));
//                subT2.addCell(one);
//                subT2.addCell(new Paragraph(""));
//                subT2.addCell(one);
//                subT2.addCell(new Paragraph("Prepared By", fontInfoHead));
//                subT2.addCell(new Paragraph(""));
//                subT2.addCell(new Paragraph("Verified By", fontInfoHead));
//                subT2.addCell(new Paragraph(""));
//                subT2.addCell(new Paragraph("Approved By", fontInfoHead));
//                subT2.addCell(new Paragraph(""));
//                subT2.addCell(new Paragraph(""));
//                subT2.addCell(new Paragraph(""));
//                subT2.addCell(new Paragraph(""));
//                subT2.addCell(new Paragraph(""));
//                subT2.addCell(new Paragraph(""));
//                subT2.addCell(new Paragraph("Received By:", fontInfo));
//                subT2.addCell(new Paragraph(""));
//                subT2.addCell(new Paragraph("Received Date:", fontInfo));
//                subT2.addCell(new Paragraph(""));
//
//                mainT.addCell(subT2);
//
//                doc.add(mainT);
//                doc.newPage();
//              }
              
              doc.close();
              }catch(Exception e){
                  e.printStackTrace();
              }
          
          return NONE;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return NONE;
  }  

    public void setSelected(String selected) {
        this.selected = selected;
    }    

    public String getLoc() {
        return loc;
    }
  

}
